package com.iwunu.auth.resolver;

import com.alibaba.fastjson.JSON;
import com.iwunu.auth.anno.CurrentUser;
import com.iwunu.auth.helper.JwtTokenHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 当前用户方法参数处理
 * @author vivi207
 * @create 2018年7月17日 下午4:10:49
 */
@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
	private final static Logger LOGGER = LoggerFactory.getLogger(CurrentUserArgumentResolver.class);

	@Autowired
	private JwtTokenHelper jwtTokenHelper;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(CurrentUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		LOGGER.debug("get jwt header key:{}", jwtTokenHelper.getJwtConfig().getHeaderKey());
		String authorization = webRequest.getHeader(jwtTokenHelper.getJwtConfig().getHeaderKey());
		String json = jwtTokenHelper.read(authorization);
		LOGGER.debug("get jwt authorization:{}", json);

		CurrentUser anno = parameter.getParameterAnnotation(CurrentUser.class);
		if(json==null || "".equals(json)) {
			if(anno.required() ) {
				throw anno.exception().newInstance();
			} else {
				return null;
			}
		}
		return JSON.parseObject(json, parameter.getParameterType());
	}

}
